package com.settlement.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.settlement.system.common.annotation.PreventDuplicateSubmit;
import com.settlement.system.common.constant.ExcelConstants;
import com.settlement.system.common.result.PageResult;
import com.settlement.system.common.result.Result;
import com.settlement.system.listener.easyexcel.SysVoucherListener;
import com.settlement.system.model.entity.SysVoucher;
import com.settlement.system.model.form.SysVoucherForm;
import com.settlement.system.model.query.SysVoucherItemQuery;
import com.settlement.system.model.query.SysVoucherQuery;
import com.settlement.system.model.vo.SysVoucherImportVo;
import com.settlement.system.model.vo.SysVoucherItemVo;
import com.settlement.system.service.SysVoucherService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 * 凭证主表 前端控制器
 * </p>
 *
 * @author huangrensen
 * @since 2024-08-26
 */
@RestController
@RequestMapping("/api/v1/voucher")
@RequiredArgsConstructor
public class SysVoucherController {

    private final SysVoucherService sysVoucherService;

    @GetMapping("/page")
    public PageResult<SysVoucher> getPage(@ParameterObject SysVoucherQuery queryParams) {
        Page<SysVoucher> result = sysVoucherService.getPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "获取凭证明细", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/getItems/{voucherId}")
    public PageResult<SysVoucherItemVo> getItems(@ParameterObject SysVoucherItemQuery queryParams, @Parameter(description = "凭证ID") @PathVariable Long voucherId) {
        Page<SysVoucherItemVo> page = sysVoucherService.getItems(voucherId, queryParams);
        return PageResult.success(page);
    }

    @Operation(summary = "保存凭证主表", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping
    @PreventDuplicateSubmit
    @PreAuthorize("@ss.hasPerm('sys:voucher:save')")
    public Result<?> saveSysVoucher(@RequestBody @Valid SysVoucherForm sysVoucherForm) {
        boolean result = sysVoucherService.saveSysVoucher(sysVoucherForm);
        return Result.judge(result);
    }

    @Operation(summary = "生成凭证", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/generate/{month}/{companyCode}")
    @PreventDuplicateSubmit
    @PreAuthorize("@ss.hasPerm('sys:voucher:generate')")
    public Result<?> generate(@PathVariable String month, @PathVariable String companyCode) {
        sysVoucherService.generate(month, companyCode);
        return Result.success();
    }

    @Operation(summary = "获取凭证主表信息", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/{id}/form")
    public Result<SysVoucherForm> getSysVoucherFormData(@Parameter(description = "主键ID") @PathVariable Long id) {
        SysVoucherForm sysVoucher = sysVoucherService.getSysVoucherFormData(id);
        return Result.success(sysVoucher);
    }



    @Operation(summary = "删除凭证主表", security = {@SecurityRequirement(name = "Authorization")})
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:voucher:delete')")
    public Result<?> deleteSysVoucher(@Parameter(description = "ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        boolean result = sysVoucherService.deleteSysVoucher(ids);
        return Result.judge(result);
    }

    @Operation(summary = "凭证主表导入", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("/sysVoucherImport")
    @PreAuthorize("@ss.hasPerm('sys:voucher:import')")
    @PreventDuplicateSubmit
    public Result<?> sysVoucherImport(@RequestParam("file") MultipartFile file) throws Exception {
        SysVoucherListener listener = new SysVoucherListener();
        EasyExcelFactory.read(file.getInputStream(), SysVoucherImportVo.class, listener).sheet(0).doRead();
        List<SysVoucherImportVo> list = listener.getVos();
        if (list == null || list.size() == 0) {
            return Result.success();
        }
        sysVoucherService.importData(list);
        return Result.success();
    }

    @Operation(summary = "导出凭证主表", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/_export")
    @PreAuthorize("@ss.hasPerm('sys:voucher:export')")
    @PreventDuplicateSubmit
    public void export(@RequestParam("voucherYear") String voucherYear, @RequestParam("voucherMonth") String voucherMonth, HttpServletResponse response) throws IOException {
        String fileName = "凭证导出模板.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        String templateFileName = ExcelConstants.EXCEL_TEMPLATE_DIR + File.separator + fileName;
        List<SysVoucherImportVo> sysVoucherList = sysVoucherService.findByMonth(voucherYear, voucherMonth);
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(templateFileName);
        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(inputStream).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            excelWriter.fill(sysVoucherList, writeSheet);
        }
    }
}

